package com.liuyingxing.javaSpringCloudAccount.dao;

import com.liuyingxing.entity.account.User;
import com.liuyingxing.entity.common.SearchBean;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * @File UserDao.java
 * @Auth liuxing
 * @Date 2021/8/22 10:36
 * @Email liuxing997@foxmail.com
 */
@Mapper
@Repository
public interface UserDao {

    //根据用户名和密码查询用户信息
    @Select("select * from account_user where user_name = #{userName} and password = #{password}")
    User getUserByUserNameAndPassword(@Param("userName") String userName, @Param("password") String password);

    //根据用户名或邮箱查询用户信息，校验是否已被使用
    @Select("select * from account_user where email = #{email} or user_name = #{userName}")
    List<User> getUserByUserNameOrEmail(@Param("email") String email, @Param("userName") String userName);

    //根据用户名查询用户信息
    @Select("select * from account_user where user_name = #{userName}")
    List<User> getUserByUserName(String userName);

    //添加用户信息
    @Insert("insert into account_user (email, user_name, password, user_image, create_date) "
            + "values (#{email}, #{userName}, #{password}, #{userImage}, #{createDate})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insertUser(User user);

    //更新用户信息
    @Update("update account_user set email = #{email}, user_name = #{userName}, "
            + "user_image = #{userImage} where id = #{id}")
    void updateUser(User user);

    //根系用户密码
    @Update("update account_user set password = #{password} where id = ${id}")
    void updateUserPassword(@Param("password") String password, @Param("id") int id);

    //根据ID查询用户信息
    @Select("select * from account_user where id = #{id}")
    @Results(id = "userResult", value = {
            @Result(column = "id", property = "id"),
            @Result(column = "id", property = "roles",
                    javaType = List.class,
                    many = @Many(select = "com.liuyingxing.javaSpringCloudAccount.dao.RoleDao.getRolesByUserId"))
    })
    User getUserById(int id);

    //删除用户信息
    @Delete("delete from account_user where id = #{id}")
    void deleteUserById(int id);

    //分页查询用户信息
    @Select("<script>"
            + "select * from account_user "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (email like '%${keyword}%' or "
            + " user_name like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<User> getUsersBySearchVo(SearchBean searchBean);
}
